<script setup>
import {
    Edit,
    Delete,
    Plus
} from '@element-plus/icons-vue'
import { ref } from 'vue'
const varietys = ref([
    {
        "id": 1,
        "variety": "猫",
    }
])
const categorys = ref({
    "id": '',
    "category": '',
    "variety": '',
    "pic": ''
});

const variety = ref('')



//文件夹式显示
import { varietyListService, varietyAddService, categoryListService, varietyUpdateService, varietyDeleteService } from '@/api/variety.js'
const varietyList = async () => {
    let result = await varietyListService();
    varietys.value = result.data;
}
const categoryList = async (id) => {
    let result = await categoryListService(id);
    categorys.value = result.data;
}
const extend = async (item) => {
    let ok = !item.expanded;
    varietys.value.forEach((folder) => {
        folder.expanded = false;
    });
    categoryList(item.id);
    item.expanded = ok;
    variety.value = item.variety;
}
varietyList()

//控制添加分类弹窗
const dialogVisible = ref(false)

//添加分类数据模型
const categoryModel = ref({
    variety: '',
    category: '',
    pic: '',
})

//上传图片
//导入token
import { useTokenStore } from '@/store/token.js';
const token = useTokenStore();
//上传成功的回调函数
const uploadSuccess = (res) => {
    categoryModel.value.pic = res.data;
}

//添加分类表单校验
const rules = {
    variety: [
        { required: true, message: '请输入宠物种类', trigger: 'blur' },
    ],
    category: [
        { required: true, message: '请输入详细种类', trigger: 'blur' },
    ],
    pic: [
        { required: true, message: '请选择图片', trigger: 'blur' },
    ]
}
//新增种类
import { ElMessage, ElMessageBox } from 'element-plus';
const addVariety = async () => {
    let result = await varietyAddService(categoryModel.value);
    ElMessage.success(result.msg ? result.msg : '添加成功')
    varietyList();
    dialogVisible.value = false;
}

const titleMsg = ref('')
const current = ref('')

//编辑
//编辑弹窗
const showEdit = (row) => {
    dialogVisible.value = true;
    titleMsg.value = "编辑分类";
    categoryModel.value.id = row.id;
    categoryModel.value.pic = row.pic;
    if (variety.value === '') {
        categoryModel.value.variety = row.variety;
    } else {
        categoryModel.value.variety = variety.value;
    }
    if (current.value === 'variety') {
        categoryModel.value.category = '';
        categoryModel.value.pic = '';
    } else {
        categoryModel.value.category = row.category;
    }
}
//编辑的响应
const updateVariety = async () => {
    let result = await varietyUpdateService(current.value, categoryModel.value);
    ElMessage.success(result.msg ? result.msg : '修改成功');
    varietyList();
    dialogVisible.value = false;
}
//清空categoryModel的数据
const clearData = () => {
    categoryModel.value.variety = '';
    categoryModel.value.category = '';
}

//删除
const remove = (id) => {
    ElMessageBox.confirm(
        '你确认要删除该分类信息吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await varietyDeleteService(current, id);
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            varietyList()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '放弃删除',
            })
        })
}

//跳转到详情页
import { useRouter } from 'vue-router';
const router = useRouter()
const goToVarietyItem = (category) => {
    router.push('/pet?category=' + category);
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>宠物种类</span>
                <div class="extra">
                    <el-button type="primary"
                        @click="current = 'category'; dialogVisible = true; titleMsg = '添加种类'; clearData();">添加种类</el-button>
                </div>
            </div>
        </template>
        <!-- 主文件夹（宠物种类）列表 -->
        <div v-for="item in varietys" :key="item.id" class="folder">
            <div class="folder-header" @click="extend(item);">
                {{ item.variety }}
                <i v-if="item.expanded" class="el-icon-arrow-up"></i>
                <i v-else class="el-icon-arrow-down"></i>
                <div style="margin-left: auto">
                    <el-button type="primary" :icon="Edit" circle @click.stop="current = 'variety'; showEdit(item)" />
                    <el-button type="danger" :icon="Delete" circle @click.stop="current = 'variety'; remove(item.id)" />
                </div>
            </div>
            <!-- 子文件夹（宠物品种）列表 -->
            <div v-if="item.expanded">
                <div v-for="category in categorys" :key="category.id" class="category-item"
                    @click="goToVarietyItem(category.category)">
                    {{ category.category }}
                    <div style="margin-left: auto">
                        <el-button type="primary" :icon="Edit" circle
                            @click.stop="current = 'category'; showEdit(category)" />
                        <el-button type="danger" :icon="Delete" circle
                            @click.stop="current = 'category'; remove(category.id)" />
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加分类弹窗 -->
        <el-dialog v-model="dialogVisible" :title="titleMsg" width="30%">
            <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
                <el-form-item label="宠物种类" prop="variety">
                    <el-input v-model="categoryModel.variety" minlength="1" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item v-if="current === 'category'" label="详细种类" prop="category">
                    <el-input v-model="categoryModel.category" minlength="1" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item v-if="current === 'category'" prop="pic" label="图片：" style="display: flex; align-items: center;">
                    <!-- 
                        auto-upload:是否自动上传
                        action: 服务器接口路径
                        name: 上传的文件字段名
                        headers: 设置上传的请求头
                        on-success: 上传成功的回调函数
                    -->
                    <el-upload :auto-upload="true" :show-file-list="false" action="/api/upload" name="file"
                        :headers="{ 'Author': token.token }" :on-success="uploadSuccess">
                        <img v-if="categoryModel.pic" :src="categoryModel.pic" style="height: 100px; width: 100px; object-fit: cover;" />
                        <el-icon v-else style="height: 100px; width: 100px;">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="titleMsg === '添加种类' ? addVariety() : updateVariety()"> 确认
                    </el-button>
                </span>
            </template>
        </el-dialog>

    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.pet-folders-container {
    padding: 20px;
}

.folder {
    margin-bottom: 10px;
}

.folder-header {
    cursor: pointer;
    user-select: none;
    padding: 5px;
    border: 1px solid #ebeef5;
    background-color: #f5f7fa;
    display: flex;
}

.category-item {
    padding: 5px;
    border: 1px solid #ebeef5;
    background-color: #fafafa;
    margin-left: 20px;
    display: flex;
}
</style>
